package com.echo.boot.leetcode.栈;

import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

/**
 * Created with IntelliJ IDEA
 * Created By CQ
 * Date: 2020/5/7
 * Time: 18:05
 * 前缀表达式
 * 中缀表达式
 * 后缀表达式
 */
public class _20_有效的括号 {
    private static Map<Character, Character> map = new HashMap<>();

    static {
        map.put('(', ')');
        map.put('{', '}');
        map.put('[', ']');
    }

    public static void main(String[] args) {
        String str = "{[{([{}])}]}";
        boolean valid = isValid2(str);
        System.out.println(valid);
    }

    public static boolean isValid(String s) {
        int length = s.length();
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < length; i++) {
            char at = s.charAt(i);
            if (at == '(' || at == '{' || at == '[') {
                stack.push(at);
            } else {
                if (stack.isEmpty()) {
                    return false;
                }
                char left = stack.pop();
                if (left == '(' && at != ')') {
                    return false;
                }
                if (left == '{' && at != '}') {
                    return false;
                }
                if (left == '[' && at != ']') {
                    return false;
                }
            }
        }
        return stack.isEmpty();
    }

    public static boolean isValid2(String s) {
        int length = s.length();
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < length; i++) {
            char at = s.charAt(i);
            if (map.containsKey(at)) {
                stack.push(at);
            } else {
                if (stack.isEmpty()) {
                    return false;
                }
                Character pop = stack.pop();
                if (at != map.get(pop)) {
                    return false;
                }

            }
        }
        return stack.isEmpty();
    }


}
